library(cluster)

erronclusters <- function(Data, nclusters)
{
	# kmeans() e pam() sao identicos

	# kmeans
	#cl <- kmeans(Data, nclusters)
	#clusters <- cl$cluster
	#centers <- cl$centers
	# nao sei como usar o silhouette com o kmeans()

	# pam
	cl <- pam(Data, nclusters)
	clusters <- cl$clustering
	centers <- cl$medoids
	erro <- mean(silhouette(cl)[,3])
	erro
}

nroclusters <- function(Data)
{
	erro_menor <- Inf
	for(n in 2:8) {
		erro <- erronclusters(Data, n)
		if(erro < erro_menor) {
			erro_menor <- erro
			nclusters <- n
		}
	}
	nclusters
}

ptscluster <- function(Data, nclusters)
{
	pts <- NULL
	cl <- pam(Data, nclusters)
	clusters <- cl$clustering
	for(n in 1:nclusters)
		pts <- c(pts, list(Data[clusters == n]))
	pts
}

# main

NCLUSTERS <- 2

print("qtos clusters? ")
s <- readLines(,1)
NCLUSTERS <- as.integer(s)

pts <- NULL
for(n in 1:NCLUSTERS) {
	x <- runif(1, -1, 1)
	y <- runif(1, -1, 1)
	SD <- 0.2
	d <- c(rnorm(50, mean = x, sd = SD), rnorm(50, mean = y, sd = SD))
	m <- matrix(d, ncol=2)
	pts <- rbind(pts, m)
}

nclusters <- nroclusters(pts)

cl <- pam(pts, nclusters)
plot(pts, col = cl$clustering, main = paste('nclusters:', nclusters))  # pontos

print(ptscluster(pts, nclusters))

print(paste('clusters:', nclusters))

